<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- v-model：绑定当前激活的tab栏 -->
      <!-- 它会找到el-tab-pane里name值一样的选中 -->
      <el-tabs v-model="activeName">
        <!-- 要有多少个tab栏，就加几个el-tab-pane -->
        <!-- label用来控制显示tab栏的标题 -->
        <!-- 每个tab栏里的内容，就放在这个el-tab-pane的双标签里面 -->
        <el-tab-pane label="角色管理" name="first">
          <!-- el-button -->
          <el-row>
            <el-button
              v-if="checkPoint('POINT-ROLE-ADD')"
              @click="showDialog = true"
              icon="el-icon-plus"
              size="small"
              type="primary"
              >新增角色</el-button>
          </el-row>
          <!-- el-table -->
          <!-- data用来绑定el-table的数据 -->
          <!-- 它是一个数组，数组有多少个元素，el-table就生成多少行 -->
          <el-table border :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="180">
            </el-table-column>
            <el-table-column prop="name" label="角色名" width="180">
            </el-table-column>
            <el-table-column prop="description" label="描述"> </el-table-column>

            <!-- 默认只能显示文字内容，如果你想放别的东西就用插槽自定义 -->
            <el-table-column prop="description" label="操作">
              <!-- 作用域插槽：拿到数据 -->
              <!-- <template slot-scope="scope">
                {{ scope.row }}
              </template> -->
              <!-- 用结构语法直接取出row属性：row属性就是这一行的数据 -->
              <template slot-scope="{ row }">
                <el-link @click="showPermission(row.id)" type="primary">分配权限</el-link>
                <el-link
                  @click="doEdit(row.id)"
                  style="margin: 0 10px"
                  type="primary"
                  >修改</el-link
                >
                <el-link v-if="checkPoint('POINT-ROLE-DELETE')"  @click="doDel(row.id)" type="primary">删除</el-link>
              </template>
            </el-table-column>
          </el-table>
          <!-- el-pagination -->
          <!-- current-change：改变页码会触发的事件 -->
          <!-- current-page： 用来设置当前页的属性 -->
          <!-- page-size： 页容量：每页显示多少条 -->
          <!-- total： 设置数据总数量 -->
          <!-- layout：指定这个分页从左到右有哪些元素 -->
          <el-pagination
            style="text-align: center"
            :current-page.sync="pageInfo.page"
            :page-size="pageInfo.pagesize"
            :total="pageInfo.total"
            layout="total, prev, pager, next"
            @current-change="getRoleList"
          />
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="second">
          <el-form
            :model="comForm"
            style="width: 450px; margin: 0 auto"
            label-width="80px"
          >
            <el-form-item label="企业名称">
              <el-input v-model="comForm.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input v-model="comForm.companyAddress" disabled></el-input>
            </el-form-item>
            <el-form-item label="公司电话">
              <el-input v-model="comForm.companyPhone" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="comForm.mailbox" disabled></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="comForm.remarks" disabled></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        :title="title"
        :visible.sync="showDialog"
        @close="cancelDialog"
      >
        <el-form ref="addForm" :model="addForm" :rules="addRules">
          <el-form-item prop="name" label="角色名称" label-width="90px">
            <el-input v-model="addForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="description" label="角色描述" label-width="90px">
            <el-input
              v-model="addForm.description"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelDialog">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog @close="cancelPerm" title="分配权限" :visible.sync="showPermDialog">
        <el-tree
          ref="tree"
          check-strictly
          :data="treeData"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="checkedKeys"
          :props="defaultProps"
        >
        </el-tree>
        <el-row type="flex" justify="center">
          <el-button @click="assinPermission" size="mini" type="primary">确定</el-button>
          <el-button @click="cancelPerm" size="mini">取消</el-button>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getRoleList,
  delRole,
  addRole,
  editRole,
  getRoleDetail,
  getCompanyDetail,
  assignPermission
} from "@/api/setting";

import { getPermissionList } from '@/api/permission'
import { transToTreeData } from '@/utils'


import { mapGetters } from "vuex";

export default {
  name: "setting",
  data() {
    return {
      currentId: '',
      // 设置默认选中的数组
      checkedKeys: [],
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      showPermDialog: false,

      comForm: {},
      showDialog: false,
      addForm: {},
      addRules: {
        name: [{ required: true, message: "请输入角色名", trigger: "blur" }],
        description: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
      },
      activeName: "first",
      tableData: [],
      pageInfo: {
        // 页码
        page: 1,
        // 页容量
        pagesize: 10,
        // 数据总量
        total: 0,
      },
    };
  },

  created() {
    this.getRoleList();
    this.getComanyInfo();
  },

  methods: {
    // 点击分配权限的确定事件
    async assinPermission () {

      // 拿到选中的权限id
      let ids = this.$refs.tree.getCheckedKeys()
      await assignPermission({
        id: this.currentId,
        permIds: ids
      })

      this.$message.success('分配权限成功！')
      this.showPermDialog = false
    },

    cancelPerm () {
      // 树形数据改为空
      this.treeData = []
      // 选中的也改为空
      this.checkedKeys = []
      this.showPermDialog = false
    },
    // 显示分配权限
    async showPermission(id) {
      // 把被点的角色id存起来
      this.currentId = id
      let res = await getPermissionList()
      // 调用递归转成树形结构赋值给tree去显示
      this.treeData = transToTreeData(res.data, '0')
      // 根据id获取当前角色详情
      let res2 = await getRoleDetail(id)
      // 设置默认选中的id
      this.checkedKeys = res2.data.permIds
      // 显示tree
      this.showPermDialog = true
    },
    
    async getComanyInfo() {
      let res = await getCompanyDetail(this.companyId);
      this.comForm = res.data;
    },
    // 加载数据
    async getRoleList() {
      let res = await getRoleList(this.pageInfo);
      this.pageInfo.total = res.data.total;
      this.tableData = res.data.rows;
    },

    // 删除的点击事件
    async doDel(id) {
      // 删除最好要问一下
      // 因为$confirm返回的就是Promise对象，所以可以用await
      // 我怎么知道点了确定？我怎么知道点了取消？
      // 以前是.then代表点了确定， .catch代表点了取消
      // .then要触发，执行的应该是Promise里的resolve（正常），取消要触发应该是reject（报错）
      try {
        await this.$confirm("确定要删除吗？");

        // 能来到这代表点了确定，就调用删除
        await delRole(id);

        // 删除成功弹出提示并加载数据
        this.getRoleList();
        this.$message.success("删除成功！");
      } catch (error) {
        console.log(error);
      }
    },

    // 确定的点击事件
    save() {
      // 整个表单验证
      this.$refs.addForm.validate(async (v) => {
        if (v) {
          if (this.addForm.id) {
            await editRole(this.addForm);
          } else {
            // 全部通过，可以发请求了
            await addRole(this.addForm);
          }

          this.getRoleList();
          this.$message.success(this.title + "成功！");
          // 隐藏对话框
          this.showDialog = false;
        }
      });
    },

    cancelDialog() {
      this.addForm = {};
      this.$refs.addForm.resetFields();
      this.showDialog = false;
    },

    // 修改的点击事件
    async doEdit(id) {
      // 先根据id获取数据
      let res = await getRoleDetail(id);
      // 再赋值给对话框的表单绑定的对象
      this.addForm = res.data;
      // 再显示对话框
      this.showDialog = true;
    },
  },

  computed: {
    ...mapGetters(["companyId"]),
    title() {
      return this.addForm.id ? "编辑角色" : "新增角色";
    },
  },
};
</script>

<style lang="scss">
.el-tabs__content {
  padding: 40px 20px;

  .el-table th {
    background-color: #fafafa;
    border-bottom: 2px solid #e8e8e8;
  }
}
</style>
